import {
  HTTP
} from '../utils/http.js'
class ClassicModel extends HTTP {
  getLatest(sCallback) {
    this.request({
      url: 'classic/latest',
      success: (res) => {
        sCallback(res)
        this._setLatestIndex(res.index)
        let key = this._getKey(res.index)
        wx.setStorageSync(key, res)
      }
    })
  }

  //获取下一个最新期刊, 获取到总体期刊数据
  //index, 第几个条目, nextOrPrevious(为上还是下), sCallback(回调函数)
  //key 确定key
  //wx.getStorageSync(this._getKey(res.index), res);
  
  getClassic(index, nextOrPrevious, sCallback) {
    // 缓存中寻找 or API 写入到缓存中
    // key 确定key
    let key = nextOrPrevious == 'next' ?
      this._getKey(index + 1) : this._getKey(index - 1)
    let classic = wx.getStorageSync(key)
    if (!classic) {
      this.request({
        url: `classic/${index}/${nextOrPrevious}`,
        success: (res) => {
          wx.setStorageSync(
            this._getKey(res.index), res)
          sCallback(res)
        }
      })
    } else {
      sCallback(classic)
    }
  }



  getNext(index, sCallback) {
    this.getClassic(index, '/next', sCallback);
  }

  //是否是第一个期刊
  isFirst(index) {
    return index == 1 ? true : false
  }

  //是否是最新期刊
  isLatest(index) {
    let latestIndex = this._getLatestIndex(index);
    // 传进来的值和本地的相等就是最新的, 否则不是
    return latestIndex == index ? true : false
  }

  //设置index
  _setLatestIndex(index) {
    wx.setStorageSync('latest', index);
  }

  //获取缓存数据
  _getLatestIndex() {
    const index = wx.getStorageSync('latest');
    return index
  }

  //获取key
  _getKey(index) {
    const key = 'classic-' + index
    return key
  }

}
export {
  ClassicModel
}